
#include "unp.h"

int main(int argc, char * argv[]) {
	hello("ok");
	printf("hello\n");
	printf("tcp server listen on port %d\n", SERV_PORT);


	SA_IN servaddr, cliaddr;
	int listenfd, connfd, clilen;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	Bind(listenfd, (SA*)&servaddr, sizeof(servaddr));
	Listen(listenfd, LISTENQ);

	// handle child process exit, otherwise it leaves  zombie process
	Signal(SIGCHLD, sig_chld);


	clilen = sizeof(cliaddr);
	printf("pid=%d\n", getpid());
	for (;;) {
		connfd = Accept(listenfd, (SA*)&servaddr, &clilen);
		printf("receive client\n");
		if (Fork() == 0) { // child process
			printf("child pid=%d\n", getpid());
			Close(listenfd);
			str_echo(connfd);
			printf("child process exit pid=%d\n", getpid());
			exit(0);
		}

		Close(connfd);
	}
	return 0;
}

/**
 * echo
 */
void str_echo(int sockfd) {
	ssize_t n;
	char buf[MAXLINE];
	for ( ; ; ) {
		n = Read(sockfd, buf, MAXLINE);
		if (n > 0) {
			printf("receive %s\n", buf);
			Write(sockfd, buf, n);
		} else {
			// reach end
			printf("reach end\n");
			break;
		}
	}
}